from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from utils.file_tools import FileTools
from utils.log_util import logger


class BasePage:
    _BASE_URL = ""

    def __init__(self, base_driver: WebDriver = None):
        if base_driver is None:
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(3)
        else:
            self.driver = base_driver
        if self._BASE_URL:
            self.driver.get(self._BASE_URL)
            self.__cookie_login()

    def __cookie_login(self):
        cookies = FileTools.read_yaml("cookie_data")
        logger.debug(f"打印cookie信息：{cookies}")
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        # 刷新界面
        self.driver.refresh()

    def find(self, by, locator=None):
        if locator:
            logger.debug(f"定位的元素为{by}-{locator}")
            # 如果传入的是正常的定位信息，则正常传参
            return self.driver.find_element(by, locator)
        else:
            logger.debug(f"定位的元素为{by}")
            # 如果传入的是一个元祖，则进行解包元祖传参
            return self.driver.find_element(*by)

    def wait_click(self, locator):
        # 添加显示等待，保证按钮可点击
        return WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(locator))

    def switch_to_new_windows(self):
        logger.debug("切换窗口")
        self.driver.switch_to.window(self.driver.window_handles[-1])

    def quit(self):
        logger.debug("退出浏览器")
        self.driver.quit()


